package com.zs.demo111.web;

import com.zs.demo111.web.fegin.IUserAction;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;

@RestController
public class IndexAction {
	@RequestMapping("index")
	public String index(HttpServletRequest httpServletRequest){
		return "index:" + httpServletRequest.getServerPort();
	}

	//user 工程
	@Resource
	RestTemplate restTemplate;
	@RequestMapping("user")
	public String user(){
		String ret = restTemplate.getForObject(
				//用加载到eureka 注册的服务器名 替代 ip+端口
				//httl://127.0.0.1:8002/user
				"http://user/user",String.class);
		return "远程访问user:" + ret;
	}

	@Resource
	IUserAction userAction;
	@RequestMapping("userByFeign")
	public String userByFeign(){
		return userAction.user();
	}

	@RequestMapping("query")
	public String query(){
		return "hello world";
	}

	@RequestMapping("helloUser")
	public String hello(String name){
		return userAction.hello(name);
	}

	@RequestMapping("addUser")
	public int add(int a,int b){
		return userAction.add(a,b);
	}

	@RequestMapping("reg")
	public User add(){
		User user = new User("张三",18,new Date(),new String[]{"唱歌","跳舞","看书"});
		return userAction.reg(user);
	}

	@RequestMapping("path/{ptest}")
	public String ptest(@PathVariable("ptest") String ptest){
		return userAction.ptest(ptest);
	}

	/*
	zuul 敏感头
	 */
	@RequestMapping("headers")
	public void headers(
			HttpServletRequest request,
			HttpServletResponse response,
			PrintWriter out){
		//将请求头参数输出为utf-8
		response.setContentType("text/html;charset=utf-8");
		out.println("<ul>");
		Enumeration<String> headerNames = request.getHeaderNames();
		while (headerNames.hasMoreElements()){
			String name = headerNames.nextElement();
			out.println("<li>");
			out.println(name+":"+request.getHeader(name));
			out.println("</li>");
		}
		out.println("</ul>");
		Cookie cookie = new Cookie("name","zhangsan");
		cookie.setMaxAge(999999);
		response.addCookie(cookie);
	}
}
